package com.portal.incurridos.persistence.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

import com.portal.incurridos.persistence.dao.CommitmentDao;
import com.portal.incurridos.persistence.enumeration.StateTransactionEnum;

/**
 * @author Alan Dávila
 * e-mail ustargab@gmail.com
 * date 26/11/2013 23:14:23
 */
@Component("commitmentDaoImpl")
public class CommitmentDaoHibernateImpl implements CommitmentDao {

	/**
	 * Managment bean of dao layer.
	 */
	@Resource(name = "sessionFactory")
    private SessionFactory factoria;

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.CommitmentDao#get(java.lang.Long)
	 */
	public final CommitmentDao get(final Long commitment) {
		Session sesion = null;
		CommitmentDao commitmentOut = null;
		try {
			sesion = factoria.getCurrentSession();
			commitmentOut = (CommitmentDao) sesion.get(CommitmentDao.class, commitment);
		} catch (Exception e) {
			commitmentOut = null;
		}
		return commitmentOut;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.CommitmentDao#create(com.portal.incurridos.persistence.dao.CommitmentDao)
	 */
	public final CommitmentDao create(final CommitmentDao commintment) {
		Session sesion = null;
		Transaction tx = null;
		CommitmentDao commitmentOut = commintment;
		try {
			sesion = factoria.getCurrentSession();
			tx = sesion.beginTransaction();
			sesion.save(commitmentOut);
			tx.commit();
			sesion.close();
		} catch (Exception e) {
			commitmentOut = null;
		}
		return commitmentOut;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.CommitmentDao#update(com.portal.incurridos.persistence.dao.CommitmentDao)
	 */
	public final StateTransactionEnum update(final CommitmentDao commitmentDao) {
		Session sesion = null;
		Transaction tx = null;
		try {
			sesion = factoria.getCurrentSession();
			tx = sesion.beginTransaction();
			sesion.update(commitmentDao);
			tx.commit();
			sesion.close();
		} catch (Exception e) {
			return StateTransactionEnum.ERROR;
		}
		return StateTransactionEnum.UPDATED;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.CommitmentDao#delete(com.portal.incurridos.persistence.dao.CommitmentDao)
	 */
	public final StateTransactionEnum delete(final CommitmentDao commitmentDao) {
		Session sesion = null;
		Transaction tx = null;
		try {
			sesion = factoria.getCurrentSession();
			tx = sesion.beginTransaction();
			sesion.delete(commitmentDao);
			tx.commit();
			sesion.close();
		} catch (Exception e) {
			return StateTransactionEnum.ERROR;
		}
		return StateTransactionEnum.DELETED;
	}

}
